<template>
  <div class="user-center">
    <front-header></front-header>
    <div class="main-content">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>个人中心</h2>
      </div>

      <div class="content-wrapper">
        <!-- 左侧导航 -->
        <el-card class="side-menu-card" shadow="hover">
          <el-menu :default-active="activeMenu" class="menu-list" @select="handleMenuSelect">
            <el-menu-item index="info">
              <i class="el-icon-user"></i>
              <span>个人信息</span>
            </el-menu-item>
            <el-menu-item index="address">
              <i class="el-icon-location"></i>
              <span>收货地址</span>
            </el-menu-item>
            <el-menu-item index="appointments">
              <i class="el-icon-date"></i>
              <span>我的专家预约</span>
            </el-menu-item>
          </el-menu>
        </el-card>

        <!-- 右侧内容区 -->
        <el-card class="content-area-card" shadow="hover">
          <!-- 个人信息 -->
          <div v-if="activeMenu === 'info'" class="info-section">
            <div class="section-header">
              <h3>个人信息</h3>
              <p class="section-desc">您可以在这里修改您的个人信息</p>
            </div>
            <el-form :model="userInfo" :rules="rules" ref="userForm" label-width="100px" class="user-form">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="userInfo.username" disabled></el-input>
              </el-form-item>
              <el-form-item label="真实姓名" prop="name">
                <el-input v-model="userInfo.name"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="userInfo.email"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="updateUserInfo">保存修改</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 收货地址 -->
          <div v-if="activeMenu === 'address'" class="address-section">
            <div class="section-header">
              <div class="header-left">
                <h3>收货地址</h3>
                <p class="section-desc">管理您的收货地址信息</p>
              </div>
              <el-button type="primary" @click="showAddressDialog('add')" icon="el-icon-plus">
                新增地址
              </el-button>
            </div>

            <div class="address-list">
              <template v-if="addresses.length === 0">
                <el-empty description="暂无收货地址" class="address-empty">
                  <el-button type="primary" @click="showAddressDialog('add')">添加地址</el-button>
                </el-empty>
              </template>
              
              <template v-else>
                <el-card v-for="address in addresses" 
                  :key="address.id" 
                  class="address-item" 
                  shadow="hover"
                >
                  <div class="address-info">
                    <h4 class="receiver">
                      <span class="name">{{ address.receiver }}</span>
                      <span class="phone">{{ address.phone }}</span>
                    </h4>
                    <p class="detail">{{ address.address }}</p>
                  </div>
                  <div class="address-actions">
                    <el-button type="text" icon="el-icon-edit" @click="showAddressDialog('edit', address)">
                      编辑
                    </el-button>
                    <el-button type="text" icon="el-icon-delete" class="delete-btn" @click="deleteAddress(address.id)">
                      删除
                    </el-button>
                  </div>
                </el-card>
              </template>
            </div>
          </div>

          <!-- 我的专家预约 -->
          <div v-if="activeMenu === 'appointments'" class="appointments-section">
            <div style="gap: 16px;">
              <ExpertMyAppointments @go-detail="goExpertDetail" />
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 地址编辑对话框 -->
    <el-dialog :title="dialogType === 'add' ? '新增地址' : '编辑地址'" :visible.sync="addressDialogVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="addressForm" :rules="addressRules" ref="addressForm" label-width="100px">
        <el-form-item label="收货人" prop="receiver">
          <el-input v-model="addressForm.receiver" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input 
            type="textarea" 
            v-model="addressForm.address"
            placeholder="请输入详细地址，如：xx省xx市xx区xx街道xx号"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import FrontHeader from '@/components/front/FrontHeader.vue'
import FrontFooter from '@/components/front/FrontFooter.vue'
import Request from '@/utils/request'
import ExpertMyAppointments from './ExpertMyAppointments.vue'

export default {
  name: 'UserCenter',
  components: {
    FrontHeader,
    FrontFooter,
    ExpertMyAppointments
  },
  data() {
    return {
      activeMenu: 'info',
      currentUser: JSON.parse(localStorage.getItem('frontUser') || '{}'),
      userInfo: {
        username: '',
        name: '',
        email: ''
      },
      rules: {
        name: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      addresses: [],
      addressDialogVisible: false,
      dialogType: 'add',
      addressForm: {
        receiver: '',
        phone: '',
        address: '',
      },
      addressRules: {
        receiver: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
      },
    }
  },
  created() {
    const userInfo = localStorage.getItem('frontUser')
    if(!userInfo){
      this.$message.warning('请先登录')
      this.$router.push('/login')
    }
    else{
      this.userInfo = JSON.parse(userInfo)
      this.getUserInfo()
      this.getAddresses()
    }
  },

  methods: {
    handleMenuSelect(index) {
      this.activeMenu = index;
    },
    goExpertDetail(expertId) {
      this.$router.push({ name: 'ExpertDetail', params: { expertId } });
    },
    async getUserInfo() {
      try {
        const userId = this.currentUser.id
        const res = await Request.get(`/user/${userId}`)
        if (res.code === '0') {
          this.userInfo = res.data
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.$message.error('获取用户信息失败')
      }
    },

    async updateUserInfo() {
      try {
        this.$refs.userForm.validate(async (valid) => {
          if (valid) {
            const res = await Request.put(`/user/${this.userInfo.id}`, this.userInfo)
            if (res.code === '0') {
              this.$message.success('个人信息更新成功')
            }
          }
        })
      } catch (error) {
        console.error('更新用户信息失败:', error)
        this.$message.error('更新用户信息失败')
      }
    },

    async getAddresses() {
      try {
        const userId = this.currentUser.id
        const res = await Request.get(`/address/user/${userId}`)
        if (res.code === '0') {
          this.addresses = res.data
        }
      } catch (error) {
        console.error('获取地址列表失败:', error)
        this.$message.error('获取地址列表失败')
      }
    },

    showAddressDialog(type, address) {
      this.dialogType = type
      this.addressDialogVisible = true
      if (type === 'edit' && address) {
        this.addressForm = {
          receiver: address.receiver,
          phone: address.phone,
          address: address.address
        }
      } else {
        this.addressForm = {
          receiver: '',
          phone: '',
          address: ''
        }
      }
    },

    async saveAddress() {
      try {
        await this.$refs.addressForm.validate()
        const userId = this.currentUser.id
        const addressData = {
          userId,
          phone: this.addressForm.phone,
          address: this.addressForm.address,
        }

        if (this.dialogType === 'add') {
          const res = await Request.post('/address', addressData)
          if (res.code === '0') {
            this.$message.success('添加地址成功')
            this.getAddresses()
          }
        } else {
          const res = await Request.put(`/address/${this.currentAddress.id}`, addressData)
          if (res.code === '0') {
            this.$message.success('更新地址成功')
            this.getAddresses()
          }
        }
        this.addressDialogVisible = false
      } catch (error) {
        console.error('保存地址失败:', error)
        this.$message.error('保存地址失败')
      }
    },

    async deleteAddress(id) {
      try {
        await this.$confirm('确定要删除该地址吗？', '提示', {
          type: 'warning'
        })
        const res = await Request.delete(`/address/${id}`)
        if (res.code === '0') {
          this.$message.success('删除地址成功')
          this.getAddresses()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除地址失败:', error)
          this.$message.error('删除地址失败')
        }
      }
    }
  }
}
</script>

<style scoped>
.user-center {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #e8f5e9 0%, #fffde7 100%);
  max-height: 100%;
}

.main-content {
  flex: 1;
  padding: 40px 0 32px 0;
  max-width: 1100px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  max-height: 100%;
  overflow: auto;
}

.page-header {
  margin-bottom: 32px;
  background: #fff;
  padding: 24px 36px;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(103, 194, 58, 0.06);
  width: 100%;
  max-width: 900px;
  display: flex;
  align-items: center;
}

.page-header h2 {
  font-size: 26px;
  font-weight: 700;
  color: #388e3c;
  margin: 0;
  position: relative;
  display: inline-block;
}

.page-header h2::after {
  content: "";
  position: absolute;
  bottom: -4px;
  left: 0;
  width: 100%;
  height: 3px;
  background: #67c23a;
  border-radius: 2px;
  opacity: 0.8;
}

.content-wrapper {
  display: flex;
  gap: 24px;
  width: 100%;
  max-width: 900px;
}

.side-menu-card {
  width: 240px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(103,194,58,0.10);
  overflow: hidden;
  padding: 0;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.menu-list {
  border-right: none;
}

.menu-list .el-menu-item {
  height: 56px;
  line-height: 56px;
  font-size: 15px;
}

.menu-list .el-menu-item i {
  font-size: 18px;
  margin-right: 12px;
}

.content-area-card {
  flex: 1;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(103,194,58,0.10);
  padding: 30px;
  min-width: 0;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
}

.header-left h3 {
  font-size: 24px;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.section-desc {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.user-form {
  max-width: 500px;
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.address-item {
  transition: all 0.3s ease;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(103, 194, 58, 0.06);
  border: none;
}

.address-item:hover {
  transform: translateY(-2px);
}

.address-info {
  flex: 1;
}

.receiver {
  margin: 0 0 12px 0;
  display: flex;
  align-items: center;
  gap: 16px;
}

.name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.phone {
  color: #606266;
  font-weight: normal;
}

.detail {
  color: #606266;
  margin: 0;
  line-height: 1.5;
}

.address-actions {
  margin-top: 16px;
  display: flex;
  gap: 16px;
}

.delete-btn {
  color: #f56c6c;
}

.el-button--primary {
  background: linear-gradient(135deg, #67c23a, #85ce61);
  border: none;
  padding: 12px 24px;
  border-radius: 24px;
  transition: all 0.3s ease;
}

.el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.address-empty {
  padding: 40px 0;
}

:deep(.el-dialog) {
  border-radius: 16px;
}
:deep(.el-dialog__header) {
  padding: 24px;
  border-bottom: 1px solid #f0f2f5;
}
:deep(.el-dialog__body) {
  padding: 24px;
}
:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f2f5;
}
:deep(.el-form-item) {
  margin-bottom: 24px;
}
:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  border-radius: 8px;
}
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-empty) {
  padding: 40px 0;
}
@media (max-width: 1000px) {
  .main-content, .page-header, .content-wrapper {
    max-width: 98vw;
    padding-left: 8px;
    padding-right: 8px;
  }
  .content-wrapper {
    flex-direction: column;
    gap: 16px;
  }
  .side-menu-card {
    width: 100%;
    margin-bottom: 16px;
  }
}
@media (max-width: 700px) {
  .main-content {
    padding: 16px 0 12px 0;
  }
  .page-header, .side-menu-card, .content-area-card {
    padding: 0;
    border-radius: 0;
    box-shadow: none;
  }
  .content-area-card {
    padding: 12px 4px;
  }
}
</style> 